package cn.exrick.xboot.base.serviceimpl

import cn.exrick.xboot.base.dto.EnterpriseEmployeeRecordJudgeAnswerDto
import cn.exrick.xboot.base.entity.EmployeeExamStatus
import cn.exrick.xboot.base.entity.EnterpriseEmployeeRecord
import cn.exrick.xboot.base.entity.Inform
import cn.exrick.xboot.base.mapper.EnterpriseEmployeeRecordMapper
import cn.exrick.xboot.base.service.*
import cn.exrick.xboot.base.vo.EnterpriseEmployeeRecordVo
import cn.exrick.xboot.core.common.utils.PageUtil
import cn.exrick.xboot.core.common.utils.ResultUtil
import cn.exrick.xboot.core.common.utils.SecurityUtil
import cn.exrick.xboot.core.common.utils.ToolUtil
import cn.exrick.xboot.core.common.vo.PageVo
import cn.exrick.xboot.core.common.vo.Result
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.google.common.collect.Maps
import lombok.extern.slf4j.Slf4j
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*

/**
 * 企业员工考试记录接口实现
 * @author Fei
 */
@Slf4j
@Service
@Transactional
open class IEnterpriseEmployeeRecordServiceImpl : ServiceImpl<EnterpriseEmployeeRecordMapper?, EnterpriseEmployeeRecord?>(), IEnterpriseEmployeeRecordService {


    @Autowired
    private lateinit var iSecurityAdvisorExamContentService: ISecurityAdvisorExamContentService

    @Autowired
    private lateinit var securityUtil: SecurityUtil

    @Autowired
    private lateinit var enterpriseEmployeeService: IEnterpriseEmployeeService

    @Autowired
    private lateinit var iSecurityAdvisorJobTrainService: ISecurityAdvisorJobTrainService

    @Autowired
    private lateinit var iSecurityAdvisorJobTrainPartService: ISecurityAdvisorJobTrainPartService

    @Autowired
    private lateinit var iInformService: IInformService

    @Autowired
    private lateinit var iExamRoomService: IExamRoomService

    @Autowired
    private lateinit var iEmployeeExamStatusService: IEmployeeExamStatusService

    override fun createOrUpdateEnterpriseEmployeeRecord(enterpriseEmployeeRecord: EnterpriseEmployeeRecord): Result<Any?>? {

        return try {

            iSecurityAdvisorJobTrainPartService.getById(enterpriseEmployeeRecord.jobTrainPartId)?.apply {

                enterpriseEmployeeRecord.jobTrainId = jobTrainId
            }

            if (enterpriseEmployeeRecord.TestScore == 100) {

                enterpriseEmployeeRecord.completeTrain = true
            }
            saveOrUpdate(enterpriseEmployeeRecord)

            if (list(KtQueryWrapper(EnterpriseEmployeeRecord::class.java)
                            .eq(EnterpriseEmployeeRecord::jobTrainPartId, enterpriseEmployeeRecord.jobTrainPartId)
                            .eq(EnterpriseEmployeeRecord::TestScore, 100)
                            .eq(EnterpriseEmployeeRecord::createBy, securityUtil.currUser.id)).size == 3) {

                //创建消息通知
                iInformService.save(Inform().apply {

                    title = "正式考试通知"
                    content = iExamRoomService.getExamRoomLastByAreaId(securityUtil.currUser.areaId)?.let {

                        "尊敬的" + securityUtil.currUser.nickname + "员工您好,恭喜您获得正式考试资格, 考场为:" + it.examName +  "请尽快前往" + it.examAddress + "参加考试!"
                    }
                    informType = 2
                    informToUserId = securityUtil.currUser.id
                })
            }

            //更新考试状态表
            iEmployeeExamStatusService.getOne(KtQueryWrapper(EmployeeExamStatus::class.java)
                    .eq(EmployeeExamStatus::jobTrainId, enterpriseEmployeeRecord.jobTrainId)
                    .eq(EmployeeExamStatus::createBy, securityUtil.currUser.id))?.let {

                it.endTime = Date()
                iEmployeeExamStatusService.updateById(it)
            }

            ResultUtil.success("操作成功")
        }catch (e: Exception) {

            ResultUtil.error(e.message)
        }
    }

    override fun getEmployeeExamRecordByUserIdAndLast(employeeUserId: String): EnterpriseEmployeeRecord? {

        return getOne(KtQueryWrapper(EnterpriseEmployeeRecord::class.java).eq(EnterpriseEmployeeRecord::createBy, enterpriseEmployeeService.getUserIdByEmployeeId(employeeUserId))
                .orderByDesc(EnterpriseEmployeeRecord::createTime).last("limit 1"))
    }


    override fun judgeAnswerRightOrFalse(enterpriseEmployeeRecordJudgeAnswerDto: EnterpriseEmployeeRecordJudgeAnswerDto): Result<Boolean>? {

        return iSecurityAdvisorExamContentService.getById(enterpriseEmployeeRecordJudgeAnswerDto.examContentId)?.run {

            if (rightAnswer.equals(enterpriseEmployeeRecordJudgeAnswerDto.chooseAnswer)) ResultUtil.data(true, "回答正确")
            else ResultUtil.data(false, "回答错误")
        }
    }

    override fun getEmployeeExamRecord(pageVo: PageVo, jobTrainPartId: String?): Result<MutableMap<String, Any?>>? {

       return ToolUtil.setListToNul(list(KtQueryWrapper(EnterpriseEmployeeRecord::class.java).eq(EnterpriseEmployeeRecord::createBy, securityUtil.currUser.id)
               .eq(ToolUtil.isNotEmpty(jobTrainPartId), EnterpriseEmployeeRecord::jobTrainPartId, jobTrainPartId)
                .orderByDesc(EnterpriseEmployeeRecord::createTime)))?.run {

            val result: MutableMap<String, Any?> = Maps.newHashMap()
            result["size"] = size
            result["content"] = PageUtil.listToPage(pageVo, mapNotNull { EnterpriseEmployeeRecordVo().apply {
                ToolUtil.copyProperties(it, this)
            } }.toMutableList())
           result["jobTrainPartTitle"] = jobTrainPartId?.let { iSecurityAdvisorJobTrainPartService.getById(it)?.trainPartTitle }

            ResultUtil.data(result, "获取考试记录成功")
        } ?: ResultUtil.error(201, "暂无数据！")
    }
}